package my.engine.core;

import my.engine.utils.SettingsUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * User: emikolenko
 * Date: 13.03.2008
 * Time: 14:31:27
 */
public class AdminUserFilter implements Filter {

    private static ThreadLocal<Boolean> threadLocal = new ThreadLocal<Boolean>();

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();

        if (request.getParameter("action") != null) {
            String action = request.getParameter("action");
            if (action.equals("login")) {
                String login = request.getParameter(Consts.login);
                String passwd = request.getParameter(Consts.passwd);

                if (checkAccount(login, passwd)) {
                    session.setAttribute(Consts.userIsAdmin, true);
                }

            } else if (action.equals("logout")) {
                session.setAttribute(Consts.userIsAdmin, false);
            }
        }

        if (session.getAttribute(Consts.userIsAdmin) == null) {
            session.setAttribute(Consts.userIsAdmin, false);
            threadLocal.set(false);
            request.setAttribute("isUserAdmin", false);
        } else {
            Boolean isAdmin = (Boolean) session.getAttribute(Consts.userIsAdmin);
            threadLocal.set(isAdmin);
            request.setAttribute("isUserAdmin", isAdmin);
        }

        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            threadLocal.remove();
        }
    }

    public void destroy() {
    }

    public static boolean isUserAdmin() {
        return threadLocal.get();
    }

    private boolean checkAccount(String login, String password) {
        Map<String, String> props = SettingsUtil.getPortalProps();
        return login.equals(props.get(Consts.login)) && password.equals(props.get(Consts.passwd));
    }
}
